//
//  MyQRCodeWebVC.m
//  ZITHER
//
//  Created by weixin on 2018/12/12.
//  Copyright © 2018 weixn. All rights reserved.
//

#import "MyQRCodeWebVC.h"
#import "SGQRCode.h"
#import "ZYShareView.h"
#import <UShareUI/UShareUI.h>
#import "WBQRCodeVC.h"
//#import "WBQRCodeVC.h"

@interface MyQRCodeWebVC ()

// 样式1 返回按钮
@property(nonatomic,strong)UIButton *navStyle1PopBtn;


@property (nonatomic,strong)UIWebView * webview;

/** h5 iOS 互相交互 */
@property (nonatomic,strong)JSContext *context;

@property (nonatomic,strong)BaseImageV * img;
@property (nonatomic,strong)BaseLab * titleName;

@property (nonatomic,copy)NSString *shareUrl;
@property (nonatomic,copy)NSString *shareTitle;
@property (nonatomic,copy)NSString *shareContent;

@end

@implementation MyQRCodeWebVC

//NSString * const JS_BRIDGE_NAME = @"JSBridge";
//key of the Java Script Core Context in web view
//NSString * const JS_CONTEXT_PATH = @"documentView.webView.mainFrame.javaScriptContext";
//UserAgent:cztecwatch

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNav];
    [self.view addSubview:self.webview];
    if (_navStyle1PopBtn) {
        [self.view bringSubviewToFront:_navStyle1PopBtn];
    }
//    NSURL *url = [NSURL URLWithString:@"http://192.168.0.152:8082/#/activity/merchant"];
    [self context];
    
    //    self.webview
    
}

-(void)setUrl:(NSString *)url{
    
    _url = url;
    
    [self setWebUrl:url];

}
#pragma mark - web样式
-(void)setNav{
    switch (_navStyle) {
        case 1:
        {
            [self.baseNavigationView setHiddenNav:NO VC:self];
            self.baseNavigationView.isShowShadow = YES;
            [self.baseNavigationView NavigationBarStyle:1];
            
            if (self.title2.length>0) {
                self.img.hidden= YES;
                self.baseNavigationView.navViewStyle.title.text = self.title2;
                return;
            }
            
            self.baseNavigationView.navViewStyle.title.text = kUSER_INFO_MANAGER.nickName;
            self.baseNavigationView.leftButton1.hidden = YES;
            self.baseNavigationView.navViewStyle.isShowShadow = NO;
            self.baseNavigationView.bottomLineView.hidden = YES;
            
            self.titleName = self.baseNavigationView.navViewStyle.title;
            
            self.titleName.frame =CGRectMake(0, 0, 200,20);
            self.titleName.center = self.baseNavigationView.navViewStyle.center;
            self.titleName.centerY = self.baseNavigationView.navViewStyle.centerY+centerYH;
            
            self.img = [[BaseImageV alloc]initializeFrame:CGRectMake(0, 0, 0, 0) contentMode:2];
            [self.img sd_setImage:kUSER_INFO_MANAGER.avatar];
            [self.img setRound:25/2.0];
            self.img.frame =CGRectMake(0, 0, 25,25);
            self.img.center = self.baseNavigationView.navViewStyle.center;
            self.img.centerY = self.baseNavigationView.navViewStyle.centerY+centerYH;
            [self.baseNavigationView.navViewStyle addSubview:self.img];
            
            CGFloat textW = [NSString textWidth:kUSER_INFO_MANAGER.nickName font:17 height:17];///2.0
            
            self.titleName.centerX =self.baseNavigationView.navViewStyle.centerX-(25+10+ textW)/2.0+25+10;
            self.img.centerX = self.baseNavigationView.navViewStyle.centerX-(25+10+ textW)/2.0+12.5;
            [self.titleName mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self.img.mas_right).offset(10);
                make.centerY.mas_equalTo(self.img.mas_centerY).offset(0);
            }];
        }
            break;
        case 2:
        {
            [self.baseNavigationView setHiddenNav:YES VC:self];
            [self.view addSubview:self.navStyle1PopBtn];
            [self.navStyle1PopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(30, 30));
                make.top.equalTo(self.view.mas_top).offset(kStatusBarHeight + 5);
                make.left.equalTo(self.view.mas_left).offset(5);
            }];
            
        }
            break;
        case 3:
        {
            [self.baseNavigationView NavigationBarStyle:1];
            self.baseNavigationView.leftButton1.hidden = YES;
          //  self.baseNavigationView.navViewStyle.title.text = self.title;
            [self.baseNavigationView setHiddenNav:NO VC:self];
        }
        default:
            break;
    }

}

- (void)settitle2:(NSString *)title2{
    _title2 = title2;
    switch (_navStyle) {
        case 1:
            self.baseNavigationView.navViewStyle.title.text = title2;
            break;
        case 2:
            self.title = _title2;
            break;
        case 3:
            self.baseNavigationView.navViewStyle.title.text = title2;
            break;
            
        default:
            break;
    }
    
}

#pragma mark - ---
-(void)setWebUrl:(NSString *)url1{
  
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *customUserAgent = @"cztecwatch";
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":customUserAgent}];
        NSURL *url = [NSURL URLWithString:url1];
        NSURLRequest * request = [NSURLRequest requestWithURL:url
                                                  cachePolicy:NSURLRequestUseProtocolCachePolicy
                                              timeoutInterval:10.f];
        [self.webview loadRequest:request];
        [self.webview reload];
        
//        [self context];

    });
    
}

- (UIWebView *)webview{
    
    if (!_webview) {
        
        switch (_navStyle) {
            case 1:
            {
                _webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, NaviHeight, kScreenW, kScreenH-NaviHeight)];
            }
                break;
            case 2:
            {
                _webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, -(NaviHeight-44), kScreenW, kScreenH+20)];
            }
                break;
            case 3:
            {
                _webview = [[UIWebView alloc]initWithFrame:CGRectMake(0, NaviHeight, kScreenW, kScreenH-NaviHeight)];
            }
                break;
            default:
                break;
        }
        _webview.backgroundColor = [UIColor randomColor];
        
        _webview.opaque = NO;
        
        _webview.scrollView.pagingEnabled = NO;
        
        _webview.delegate = self;
        
        _webview.scrollView.bounces = NO;
        
        _webview.scrollView.showsHorizontalScrollIndicator = NO;
        
        _webview.scrollView.showsVerticalScrollIndicator = NO;
        
    }
    return _webview;
}


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    [self context];

    NSLog(@"%@",[NSString stringWithFormat:@"tokenReady('%@')",kUSER_INFO_MANAGER.token]);
    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    NSString *textJS = [NSString stringWithFormat:@"tokenReady('%@')",kUSER_INFO_MANAGER.token];
    [_context evaluateScript:textJS];
 
}

-(JSContext *)context{
//    if (!_context) {
    
        _context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        
        //        JSTestObjext *test = [JSTestObjext new];
        _context[@"JSObjectProtocol"] = self;
    
        
//    }
    return _context;
}

-(void)scanQrCode{

    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新，
        
        __weak __typeof(self)weakSelf = self;
        WBQRCodeVC *WBVC = [[WBQRCodeVC alloc] init];
        [weakSelf QRCodeScanVC:WBVC];
        
        [WBVC setBlock:^(NSString *url) {
            
            //            MyQRCodeWebVC * vc = [[MyQRCodeWebVC alloc]init];
            //            [self.navigationController pushViewController:vc animated:YES];
            //            vc.url = url;
            //            vc.title2 = title;
            
            //            NSString *textJS = [NSString stringWithFormat:@"scan('%@')",@"0477CA5CFDB311E8BDBA5254005876C0"];
            //            [self.context evaluateScript:textJS];
            //            NSLog(@"");
            //            if ([url containsString:@"cztec"]) {
            //                MyQRCodeWebVC * vc = [[MyQRCodeWebVC alloc]init];
            //                [self.navigationController pushViewController:vc animated:YES];
            //                self.url = url;
            
            [self setWebUrl:url];
            //            }
        }];
        
        
        
        //        /// 创建二维码扫描
        //        SGQRCodeObtainConfigure *configure = [SGQRCodeObtainConfigure QRCodeObtainConfigure];
        //
        //        SGQRCodeObtain * obtain = [SGQRCodeObtain QRCodeObtain];
        //
        //        [obtain establishQRCodeObtainScanWithController:weakSelf configure:configure];
        //        // 二维码扫描回调方法
        //        [obtain setBlockWithQRCodeObtainScanResult:^(SGQRCodeObtain *obtain, NSString *result) {
        //            NSLog(@"二维码回掉方法");
        //            NSLog(@"");
        //        }];
        //        // 二维码扫描开启方法: 需手动开启
        //        [obtain startRunningWithBefore:^{
        //            // 在此可添加 HUD
        //        } completion:^{
        //            // 在此可移除 HUD
        //        }];
        //        // 根据外界光线强弱值判断是否自动开启手电筒
        //        [obtain setBlockWithQRCodeObtainScanBrightness:^(SGQRCodeObtain *obtain, CGFloat brightness) {
        //            NSLog(@"根据外界光线强弱值判断是否自动开启手电筒");
        //            NSLog(@"");
        //        }];
        //
        //        /// 从相册中读取二维码
        //        [obtain establishAuthorizationQRCodeObtainAlbumWithController:weakSelf];
        //        // 从相册中读取图片上的二维码回调方法
        //        [obtain setBlockWithQRCodeObtainAlbumResult:^(SGQRCodeObtain *obtain, NSString *result) {
        //            NSLog(@"从相册中读取图片上的二维码回调方法");
        //            NSLog(@"");
        //        }];
        
    });
    
}


- (void)QRCodeScanVC:(UIViewController *)scanVC {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (status) {
            case AVAuthorizationStatusNotDetermined: {
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            [self.navigationController pushViewController:scanVC animated:YES];
                        });
                        NSLog(@"用户第一次同意了访问相机权限 - - %@", [NSThread currentThread]);
                    } else {
                        NSLog(@"用户第一次拒绝了访问相机权限 - - %@", [NSThread currentThread]);
                    }
                }];
                break;
            }
            case AVAuthorizationStatusAuthorized: {
                [self.navigationController pushViewController:scanVC animated:YES];
                break;
            }
            case AVAuthorizationStatusDenied: {
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - SGQRCodeExample] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                [alertC addAction:alertA];
                [self presentViewController:alertC animated:YES completion:nil];
                break;
            }
            case AVAuthorizationStatusRestricted: {
                NSLog(@"因为系统原因, 无法访问相册");
                break;
            }
                
            default:
                break;
        }
        return;
    }
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertC addAction:alertA];
    [self presentViewController:alertC animated:YES completion:nil];
}

#pragma mark - 定好的js方法
/*
 * 本次活动内容 H5需要用到的原生方法：
 1. 方法名：goNextPage 说明：H5用于跳转页面， 参数 goNextPage(string title,string url,boolean isFull,string color')
 1. 方法名：toShare 说明：H5用于分享活动页面， 参数 toShare(string title,string text,string url)
 */
- (void)goNextPage:(NSString *)title :(NSString *)url :(BOOL)isFull :(NSString *)color {
        MyQRCodeWebVC * vc = [[MyQRCodeWebVC alloc]init];
    if (isFull) {
        vc.navStyle = 2;
    } else {
        vc.navStyle = 3;
    }
    //自定义系统默认的pop动画
    
CATransition *animation = [CATransition animation];
[animation setDuration:0.3];
//主要的页面切换显示形式
[animation setType: kCATransitionPush];
//设置了页面的旋转
[animation setSubtype: kCATransitionFromRight];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    dispatch_async(dispatch_get_main_queue(), ^{
       [self.navigationController.view.layer addAnimation:animation forKey:nil];
    });


        [self.navigationController pushViewController:vc animated:NO];
        vc.url = url;
        vc.title2 = title;
}
- (void)toShare:(NSString *)title :(NSString *)text :(NSString *)url {
    
    _shareUrl = url;
    _shareTitle = title;
    _shareContent = text;
    
    NSMutableArray *shareItemsArray = [[NSMutableArray alloc]init];
    NSMutableArray *functionItemsArray = [[NSMutableArray alloc]init];
    NSArray *shareItemsTitleArray = @[@"分享朋友圈",@"分享微信",@"分享QQ",@"分享QQ空间",@"分享微博"];
    NSArray *shareItemsTitle2Array = @[@"分享_朋友圈",@"分享_微信",@"分享_qq",@"分享_QQ空间",@"分享_微博"];
    NSArray *shareItemsTitle3Array = @[@"2",@"1",@"4",@"5",@"0"];
    
    NSArray *functionItems1Array = @[@"分享链接"];
    NSArray *functionItems2Array = @[@"分享_链接"];
    NSArray *functionItems3Array = @[@"1024"];
    
    
    
    for (int i = 0; i<shareItemsTitleArray.count; i++) {
        if ([[UMSocialManager defaultManager]isInstall:i]) {
            ZYShareItem *item = [ZYShareItem itemWithTitle:shareItemsTitleArray[i]
                                                      icon:shareItemsTitle2Array[i]
                                                   handler:^{[self itemAction:shareItemsTitle3Array[i]];}];
            [shareItemsArray addObject:item];
        }
    }
    
    for (int i = 0; i<functionItems1Array.count; i++) {
        ZYShareItem *itemCustom1 = [ZYShareItem itemWithTitle:functionItems1Array[i]
                                                         icon:functionItems2Array[i]
                                                      handler:^{ [self itemAction:functionItems3Array[i]];
                                                      }];
        [functionItemsArray addObject:itemCustom1];
    }
    
    // 创建shareView
    ZYShareView *shareView = [ZYShareView shareViewWithShareItems:shareItemsArray
                                                    functionItems:functionItemsArray];
    // 弹出shareView
    [shareView show];
}

- (void)itemAction:(NSString *)title
{
    NSLog(@"%@", title);
    NSInteger index=  [title integerValue];
    if (index == 1024) {
        UIPasteboard * pastboard = [UIPasteboard generalPasteboard];
        pastboard.string = [NSString stringWithFormat:@"%@",self.shareUrl];
        
        [Tools showTips:@"复制链接成功"];
    } else{
        if (!kUSER_INFO_MANAGER.userIsLogin) {
            [Tools pushSinge];
        }else{
            [self shareWebPageToPlatformType:index];
        }
    }
}

- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
   // NSString *name = [NSString stringWithFormat:@"%@ 的分享",kUSER_INFO_MANAGER.nickName];
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:_shareTitle descr:_shareContent thumImage:[UIImage imageNamed:@"icon"]];
    //设置网页地址
    
    shareObject.webpageUrl = [NSString stringWithFormat:@"%@",self.shareUrl];
    
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
    
}
//-(void)goNextPage:(NSString*)title url:(NSString*)url{
//    [Tools showTips:title];
//    [Tools showTips:url];
//}

//-(void)goNext:(NSString*)title Page:(NSString*)url{
////    [Tools showTips:url];
////    [Tools showTips:title];
//
////    self.url = url;
//    MyQRCodeWebVC * vc = [[MyQRCodeWebVC alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
//    vc.url = url;
//    vc.title2 = title;
//}



//-(void)goNextPage:(NSString*)url{
////    [Tools showTips:title];
//    [Tools showTips:url];
//}

#pragma mark - lazy
- (UIButton *)navStyle1PopBtn {
    if (!_navStyle1PopBtn) {
        _navStyle1PopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_navStyle1PopBtn setImage:[UIImage imageNamed:@"pgc_btn_back_white"] forState:UIControlStateNormal];
        [_navStyle1PopBtn addTarget:self action:@selector(popAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _navStyle1PopBtn;
}
- (void)popAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
@end
